package com.fas.hehe.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.fas.core.BaseController;
import com.fas.core.constant.R;
import com.fas.core.plugin.jfinal.route.ControllerBind;
import com.fas.core.plugin.shiro.kit.FasShiroKit;
import com.fas.core.plugin.shiro.kit.PasswordKit;
import com.fas.core.util.datadict.DataDic;
import com.fas.hehe.system.model.Organization;
import com.fas.hehe.system.model.User;
import com.fas.hehe.system.model.UserDetail;
import com.fas.hehe.system.service.OrganizationService;
import com.fas.hehe.system.service.UserService;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * 
 * @ClassName: UserController
 * @Description: 用户管理
 * @Copyright: Copyright (c) 2016 FAS
 * @anthor yixiaoping<thinker1013@163.com>
 * @since 2016年1月28日 下午11:52:56
 * @version V1.0
 */
@RequiresAuthentication
@ControllerBind(controllerKey = "/system/user", viewPath = "/system/user")
public class UserController extends BaseController {

	public UserService userService;
	public OrganizationService organizationService;

	// 【异步】分页查询
	@RequiresPermissions(value = { R.Authority.User.QUERY }, logical = Logical.AND)
	public void list() {
		Page<Record> recordList = userService.queryPage(this.buildPageRequest());
		this.returnPage(recordList);
	}

	// 用户创建预处理
	@Override
	@RequiresPermissions(value = { R.Authority.User.CREATE }, logical = Logical.AND)
	protected void beforeAdd() throws Exception {
		Long orgId = this.getLoginUser().getCompanyId();
		List<Organization> orgList = organizationService.findSubOrgListById(orgId);
		ArrayList<DataDic> newList = new ArrayList<DataDic>();
		for (Organization org : orgList) {
			String orgType = org.getOrgType();
			if (R.Dict.ORG_COM.equals(orgType) || R.Dict.ORG_BR.equals(orgType))
				newList.add(new DataDic(org.getId().toString(), org.getName()));
		}
		this.setAttr("orgList", newList);
		super.beforeAdd();
	}

	// 用户修改预处理
	@Override
	@RequiresPermissions(value = { R.Authority.User.UPDATE }, logical = Logical.AND)
	protected void beforeEdit() throws Exception {
		Long orgId = this.getLoginUser().getCompanyId();
		List<Organization> orgList = organizationService.findSubOrgListById(orgId);
		ArrayList<DataDic> newList = new ArrayList<DataDic>();
		for (Organization org : orgList) {
			String orgType = org.getOrgType();
			if (R.Dict.ORG_COM.equals(orgType) || R.Dict.ORG_BR.equals(orgType))
				newList.add(new DataDic(org.getId().toString(), org.getName()));
		}
		Long userId = this.getParaToLong(R.Key.PK);

		User user = (User) this.findById(userId);
		UserDetail userDetail = userService.findUserDetailById(userId);
		this.setAttr("user", user);
		this.setAttr("userDetail", userDetail);
		this.setAttr("orgList", newList);
		super.beforeEdit();
	}

	// 保存用户信息（新增、修改时，包含用户基本信息、详细信息）
	@Override
	@RequiresPermissions(value = { R.Authority.User.CREATE, R.Authority.User.UPDATE }, logical = Logical.OR)
	public void save() throws Exception {
		User user = (User) this.getModel(User.class, "user");
		UserDetail userDetail = (UserDetail) this.getModel(UserDetail.class, "userDetail");
		userService.saveUser(user, userDetail);
		this.renderToResultPage("保存成功!");
	}

	// 删除用户
	@Override
	@RequiresPermissions(value = { R.Authority.User.DELETE }, logical = Logical.AND)
	public void delete() throws Exception {
		boolean isSuccess = userService.deleteUserById(this.getParaToLong("userId"));
		this.returnJsonResult(isSuccess);
	}

	// 旧密码校验（修改密码时需再次输入密码比对）
	@RequiresPermissions(value = { R.Authority.User.UPDATE }, logical = Logical.AND)
	public void passwordSameCheck() {
		Long userId = this.getParaToLong("userId");
		String newPassword = this.getPara("oldPassword");

		User user = (User) this.findById(userId);
		String oldPassword = user.getPassword();

		user.setPassword(newPassword);
		newPassword = PasswordKit.me().createPwd(newPassword, user.getCredentialsSalt());

		log.debug("newPassword=" + newPassword);
		log.debug("oldPassword=" + oldPassword);
		if (newPassword.equals(oldPassword)) {
			this.returnJsonResult(SUCCESS);
		} else {
			this.returnJsonResult(ERROR);
		}
	}

	// 修改密码
	@RequiresPermissions(value = { R.Authority.User.UPDATE }, logical = Logical.AND)
	public void changePassword() {
		Long userId = this.getParaToLong("userId");
		String newPassword = this.getPara("newPassword");
		boolean isSuccess = userService.changePassword(userId, newPassword);
		if (isSuccess)
			FasShiroKit.getSubject().logout();
		this.returnJsonResult(isSuccess);
	}

	// 重置密码
	@RequiresPermissions(value = { R.Authority.User.RESETPWD }, logical = Logical.AND)
	public void resetPassword() {
		String newPassword = userService.resetPassword(this.getParaToLong("userId"));
		HashMap<String, Object> returnData = new HashMap<String, Object>();
		returnData.put("newPasword", newPassword);
		if (StrKit.isBlank(newPassword)) {
			this.returnJsonResult(ERROR, "重置密码失败!", null);
		} else {
			this.returnJsonResult(returnData);
		}
	}

	// 查询用户拥有的角色
	@RequiresPermissions(value = { R.Authority.Role.QUERY }, logical = Logical.AND)
	public void findUserOfRoles() {
		List<Record> roleStateList = userService.findUserOfRolesById(this.getParaToLong("userId"));
		HashMap<String, Object> returnData = new HashMap<String, Object>();
		returnData.put("rolelist", roleStateList);
		this.returnJsonResult(returnData);
	}

	// 批量保存用户角色
	@RequiresPermissions(value = { R.Authority.Role.UPDATE, R.Authority.Role.CREATE }, logical = Logical.OR)
	public void batchSaveUserOfRole() {
		Long userId = this.getParaToLong("userId");
		userService.batchSaveUserOfRole(userId, this.getPara("roleIds"));// roleIds是角色ID字符串，多个以逗号分隔
		this.returnJsonResult(SUCCESS);
	}

	
	public void toChangePwd() throws Exception{
		this.setAttr("type", "changePwd");
		edit();
	}
	public void toShowProfile() throws Exception {
		this.setAttr("type", "showProfile");
		edit();
	}
}
